﻿using System;
using System.Linq;

namespace PodcastGenerator
{
    public class SermonBuilder : ISermonBuilder
    { 
        public ISermon Build(params Scraper.DataCell[] dataCellArray)
        {
            if (dataCellArray.Length != 6)
            {
                throw new ArgumentException("The data cell array length was not 6. The array passed was " + string.Join(",", dataCellArray.Select(p => p.InnerText)),
                    "dataCellArray");
            }

            return new Sermon()
            {
                Date = GetDate(dataCellArray[0].InnerText),
                Title = Cleanup(dataCellArray[1].InnerText),
                Pastor = Cleanup(dataCellArray[2].InnerText),
                Ref = Cleanup(dataCellArray[3].InnerText),
                DownloadUri = ExtractDownloadUri(dataCellArray[4]),
                FileSize = Cleanup(dataCellArray[5].InnerText)
            };
        }

        private static string Cleanup(string rawValue)
        {
            return rawValue.Replace("\n", string.Empty);
        }

        private static DateTime GetDate(string innerText)
        {
            try
            {
                if (innerText.Contains("/"))
                {
                    innerText = innerText.Substring(0, innerText.IndexOf("/", System.StringComparison.Ordinal));
                }

                if (innerText.Contains("("))
                {
                    innerText = innerText.Substring(0, innerText.IndexOf("(", System.StringComparison.Ordinal));
                }

                innerText = innerText.Replace(Environment.NewLine, string.Empty);

                return DateTime.ParseExact(innerText, "dd MMMM yyyy", null);
            }
            catch (FormatException)
            {
                return DateTime.MinValue;
            }
        }

        private static Uri ExtractDownloadUri(Scraper.DataCell dataCell)
        {
            try
            {
                var firstQuote = dataCell.InnerHtml.IndexOf("a href=", StringComparison.Ordinal) + 8;
                var endingQuote = dataCell.InnerHtml.IndexOf('"', firstQuote);
                return new Uri(dataCell.InnerHtml.Substring(firstQuote, endingQuote - 9));
            }
            catch (Exception )
            {
                return null;
            }
        }
    }
}